# books/views.py
from django.contrib.auth import authenticate

from hello.models import UserInfo, Drug, Manufacturer, Stock, Buyer, Sales, Supply, DrugTreatment
from hello.serializer import UserInfoSerializer, DrugSerializer, ManufacturerSerializer, StockSerializer, \
    BuyerSerializer, SalesSerializer, SupplySerializer, DrugTreatmentSerializer
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response


class UserViewSet(viewsets.ModelViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

    @action(detail=False, methods=['post'])
    def login_check(self, request, *args, **kwargs):
        username = request.data.get("username")
        password = request.data.get("password")
        role = request.data.get("role")
        user = self.queryset.filter(name__exact=username).filter(pwd__exact=password).filter(role__exact=role)
        if user:
            # 这里需要返回一个 token 或者其他形式的认证
            return Response({"message": "Login successful", "role": user.first().role}, status=status.HTTP_200_OK)
        else:
            return Response({"message": "Invalid username or password"}, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['post'])
    def check_name(self, request, *args, **kwargs):
        username = request.data.get("username")
        user = self.queryset.filter(name__exact=username)
        if user:
            return Response({"message": "Username available"}, status=status.HTTP_200_OK)
        else:
            return Response({"message": "Username already exists"}, status=status.HTTP_404_NOT_FOUND)

    @action(detail=False, methods=['get'])
    def search_by_name_pattern(self, request, *args, **kwargs):
        name_pattern = request.query_params.get('name_pattern', None)
        if not name_pattern:
            return Response({"error": "Please provide a name pattern."}, status=status.HTTP_400_BAD_REQUEST)
        users = self.queryset.filter(name__iregex=name_pattern)
        serializer = self.serializer_class(users, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def search_by_role(self, request, *args, **kwargs):
        role_pattern = request.query_params.get('role', None)
        if not role_pattern:
            return Response({"error": "Please provide a role."}, status=status.HTTP_400_BAD_REQUEST)
        users = self.queryset.filter(role__exact=role_pattern)
        serializer = self.serializer_class(users, many=True)
        return Response(serializer.data)


class DrugViewSet(viewsets.ModelViewSet):
    queryset = Drug.objects.all()
    serializer_class = DrugSerializer

    @action(detail=False, methods=['get'])
    def search_by_title_pattern(self, request, *args, **kwargs):
        title_pattern = request.query_params.get('title_pattern', None)
        if not title_pattern:
            return Response({"error": "Please provide a title pattern."}, status=status.HTTP_400_BAD_REQUEST)
            # 直接使用提供的name_pattern作为正则表达式进行匹配，Django ORM的__iregex已经处理了大小写不敏感
        drugs = self.queryset.filter(drug_name__iregex=title_pattern)
        # 序列化查询结果
        serializer = self.serializer_class(drugs, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def search_by_type(self, request, *args, **kwargs):
        type_pattern = request.query_params.get('type', None)
        if not type_pattern:
            return Response({"error": "Please provide a type."}, status=status.HTTP_400_BAD_REQUEST)
        drugs = self.queryset.filter(drug_type__exact=type_pattern)
        serializer = self.serializer_class(drugs, many=True)
        return Response(serializer.data)


class ManufactureViewSet(viewsets.ModelViewSet):
    queryset = Manufacturer.objects.all()
    serializer_class = ManufacturerSerializer


class StockViewSet(viewsets.ModelViewSet):
    queryset = Stock.objects.all()
    serializer_class = StockSerializer

    @action(detail=False, methods=['get'])
    def search_by_name_pattern(self, request, *args, **kwargs):
        name_pattern = request.query_params.get('name', None)
        if not name_pattern:
            return Response({"error": "Please provide a name pattern."}, status=status.HTTP_400_BAD_REQUEST)
        stocks = self.queryset.filter(drug_name__iregex=name_pattern)
        serializer = self.serializer_class(stocks, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def search_by_type(self, request, *args, **kwargs):
        type_pattern = request.query_params.get('type', None)
        if not type_pattern:
            return Response({"error": "Please provide a type."}, status=status.HTTP_400_BAD_REQUEST)
        stocks = self.queryset.filter(stock_warning__exact=type_pattern)
        serializer = self.serializer_class(stocks, many=True)
        return Response(serializer.data)


class BuyerViewSet(viewsets.ModelViewSet):
    queryset = Buyer.objects.all()
    serializer_class = BuyerSerializer


class SalesViewSet(viewsets.ModelViewSet):
    queryset = Sales.objects.all()
    serializer_class = SalesSerializer


class SupplyViewSet(viewsets.ModelViewSet):
    queryset = Supply.objects.all()
    serializer_class = SupplySerializer


class DrugTreatmentViewSet(viewsets.ModelViewSet):
    queryset = DrugTreatment.objects.all()
    serializer_class = DrugTreatmentSerializer

    @action(detail=False, methods=['get'])
    def search_by_name(self, request, *args, **kwargs):
        name = request.query_params.get('name', None)
        if not name:
            return Response({"error": "Please provide a name."}, status=status.HTTP_400_BAD_REQUEST)
        drugs = self.queryset.filter(treated_by__exact=name)
        serializer = self.serializer_class(drugs, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def search_by_date(self, request, *args, **kwargs):
        date = request.query_params.get('date', None)
        if not date:
            return Response({"error": "Please provide a date."}, status=status.HTTP_400_BAD_REQUEST)
        drugs = self.queryset.filter(treatment_date__exact=date)
        serializer = self.serializer_class(drugs, many=True)
        return Response(serializer.data)
